package com.taotao.sso.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taoato.sso.service.UserLoginService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
@Controller
public class UserLoginController {

	//注入服务
	@Autowired
	private UserLoginService service;
	
	@Value("${TOKEN_KEY}")
	private String TOKEN;
	/**
	 * url:/user/login
	 * 参数：username password
	 * 返回值：json
	 * 请求限定的方法：post
	 */
	@RequestMapping(value="/user/login",method=RequestMethod.POST)
	@ResponseBody
	public TaotaoResult userLogin(HttpServletRequest request,HttpServletResponse response,String username,String password) {
	    TaotaoResult result = service.userLogin(username, password);
	  
	    if(result.getStatus()==200) {
	    	 //设置token到cookie中，cookie需要跨域
		    CookieUtils.setCookie(request, response, TOKEN, result.getData().toString());
	    }
	    return result;
	}
	
	/**
	 * 解决跨域问题(spring4.1版本+)
	 * url:/user/token/{token}
	 * 参数：token
	 * 返回值：jsonp
	 * 请求限定的方法：get
	 */
	@RequestMapping(value="/user/token/{token}",method=RequestMethod.GET)
	@ResponseBody
	public Object getUserByToken(@PathVariable String token,String callback) {
		TaotaoResult result = service.getToken(token);
		
		if(StringUtils.isNotEmpty(callback)) {
			MappingJacksonValue value = new MappingJacksonValue(result);
			value.setJsonpFunction(callback);
			return value;
		}
		
		return result;
	}
	
}
